using Microsoft.AspNetCore.Mvc;
using TodoAppApi.Data;
using TodoAppApi.Models;

namespace TodoAppApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TodoItemsController : ControllerBase
    {
        private readonly TodoContext _context;

        public TodoItemsController(TodoContext context)
        {
            _context = context;
        }

        // 获取所有待办事项
        [HttpGet]
        public IActionResult GetTodos()
        {
            return Ok(_context.Todos.ToList());
        }

        // 获取单个待办事项
        [HttpGet("{id}")]
        public IActionResult GetTodoItem(int id)
        {
            var item = _context.Todos.Find(id);
            if (item == null)
            {
                return NotFound();
            }
            return Ok(item);
        }

        // 新增待办事项
        [HttpPost]
        public IActionResult CreateTodoItem([FromBody] TodoItem todoItem)
        {
            _context.Todos.Add(todoItem);
            _context.SaveChanges();
            return CreatedAtAction(nameof(GetTodoItem), new { id = todoItem.Id }, todoItem);
        }

        // 更新待办事项
        [HttpPut("{id}")]
        public IActionResult UpdateTodoItem(int id, [FromBody] TodoItem todoItem)
        {
            var existingItem = _context.Todos.Find(id);
            if (existingItem == null)
            {
                return NotFound();
            }

            existingItem.Title = todoItem.Title;
            existingItem.IsCompleted = todoItem.IsCompleted;
            _context.SaveChanges();

            return NoContent();
        }

        // 删除待办事项
        [HttpDelete("{id}")]
        public IActionResult DeleteTodoItem(int id)
        {
            var item = _context.Todos.Find(id);
            if (item == null)
            {
                return NotFound();
            }

            _context.Todos.Remove(item);
            _context.SaveChanges();

            return NoContent();
        }
    }
}
